package ovm.gui.views.schedule;

import com.vaadin.Application;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;
import com.vaadin.ui.Button;
import ovm.gui.views.AbstractEntityListView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import static ovm.application.MainApplication.*;

/**
 * Created by IntelliJ IDEA.
 * User: Jokser
 * Date: 01.06.12
 * Time: 3:44
 * To change this template use File | Settings | File Templates.
 */


public class ScheduleGeneratorView extends AbstractEntityListView {

    private Button generateButton;

    class FileDownloadResource extends FileResource {

        public FileDownloadResource(File sourceFile, Application application) {
            super(sourceFile, application);
        }

        public DownloadStream getStream() {
            try {
                final DownloadStream ds = new DownloadStream(new FileInputStream(
                        getSourceFile()), getMIMEType(), getFilename());
                ds.setParameter("Content-Disposition", "attachment; filename="+getFilename());
                ds.setCacheTime(getCacheTime());
                return ds;
            } catch (final FileNotFoundException e) {
                return null;
            }
        }
    }

    public ScheduleGeneratorView(Class entityClass, Boolean editable) {
        super(entityClass, editable);

        table.removeContainerProperty("details");
        setCaption("Генератор расписания");

        removeAllFilters();
        editButton.setVisible(false);
        saveButton.setVisible(false);

        generateButton = new Button("Сгенерировать и выгрузить в Excel");
        generateButton.addListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                String path = getApplication().getContext().getBaseDirectory().getAbsolutePath();
                event.getButton().getWindow().open(new FileDownloadResource(
                        new File(path+File.separatorChar+"schedule.xls"), getApplication()));
            }
        });

        actionsLayout.addComponent(generateButton);
    }

}
